#!/usr/bin/php
<?php

/*
 *
 * By Vlad 'Mancini' Alexa, http://vladalexa.com based on code by Kai 'Oswald' Seidler
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 675 Mass
 * Ave, Cambridge, MA 02139, USA. 
 * 
 */

ini_set('auto_detect_line_endings', TRUE);
include("keychain.php");
$keychain="AppSalesWidget";

if($argv[1]!="getdata" && $argv[1]!="setcredentials")
{
	echo "Usage: {$argv[0]} getdata [return] <user>\n";
	echo "       {$argv[0]} setcredentials [return] <user> <pass>\n";
	exit(1);
}

if($argv[1]=="setcredentials")
{
	$fp = fopen("php://stdin", "r") or die("can't read stdin");
	$username = trim(fgets($fp));
	$password = trim(fgets($fp));
	fclose($fp);

	kc_createKeyChain($keychain);
	kc_addPassword($keychain, $username, $password);
	exit;

}

$fp = fopen("php://stdin", "r") or die("can't read stdin");
$username = trim(fgets($fp));
fclose($fp);

$password=kc_getPassword($keychain,$username);
$cookie = tempnam(dirname(__FILE__), "cookie");
$ch = curl_init();

$p = "19"; //prefix changes every 3 months
$one = $p.".11";
$two = $p.".13";
$three = $p.".17";

for ($i = 0; $i <= 3; $i++){
	curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt ($ch, CURLOPT_TIMEOUT, 25);
	curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
	curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);	
	curl_setopt ($ch, CURLOPT_ENCODING,"gzip,deflate"); 
	curl_setopt ($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3");
	curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded","Accept-Charset: ISO-8859-1,utf-8","Accept-Language: en-us,en"));		

	if($i==0){
		//log in
		$url = "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/3.0.9.3.3.2.1.1.3.1.1";
		curl_setopt ($ch, CURLOPT_URL,$url);
		$postdata="theAccountName=".urlencode($username)."&theAccountPW=".urlencode($password)."&1.Continue=true";
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
		curl_setopt ($ch, CURLOPT_POST, 1);					
	}
	if($i==1){
		//get id 
		$url = "https://itts.apple.com/cgi-bin/WebObjects/Piano.woa";
		curl_setopt ($ch, CURLOPT_URL,$url);
		$postdata="hiddenSubmitTypeName=ShowDropDown&hiddenDayOrWeekSelection=Weekly&$one=Summary&$two=Weekly";
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
		curl_setopt ($ch, CURLOPT_POST, 1);					
	}	
	if($i==2 && isset($id)){
		//get week
		$url = "https://itts.apple.com/cgi-bin/WebObjects/Piano.woa/$id/0.$p";
		curl_setopt ($ch, CURLOPT_URL,$url);		
		$postdata="hiddenSubmitTypeName=ShowDropDown&$one=Summary&$two=Weekly";
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
		curl_setopt ($ch, CURLOPT_POST, 1);	
	}	
	if($i==3 && isset($id) && isset($week)){
		//get tsv
		$url = "https://itts.apple.com/cgi-bin/WebObjects/Piano.woa/$id/0.$p";
		curl_setopt ($ch, CURLOPT_URL,$url);		
		$postdata="hiddenSubmitTypeName=Download&hiddenDayOrWeekSelection=$week&$one=Summary&$two=Weekly&$three.1=$week";
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
		curl_setopt ($ch, CURLOPT_POST, 1);		
	}	

	//debug
	//echo "[Opening ".$url;
	$result = curl_exec ($ch);
	//echo " got ".strlen($result)." chars]\n";
	if (preg_match('/color=\"red\".*?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(.+?)<\/font>/', $result, $matches)){
		//echo $matches[1]."\n";
	}	
	
	//get week
	if(!isset($week) && preg_match("/name=\"".$three.".1\"><option value=\"(.*?)\">.*?<\/option>/", $result, $matches)){
		$week = urlencode($matches[1]);	
	}

	//get session id	
	if(!isset($id) && preg_match('/action="\/cgi-bin\/WebObjects\/Piano.woa\/(.*)\//', $result, $matches)){		
		$id = $matches[1];		
	}
	
	//get tsv
	if ($i==3 && preg_match("/Apple Identifier/i",$result)){
		$data = $result;
	}
	
	//do some checks
	if (preg_match("/Session /i",$result)){
		echo "Session Expired\n";
		break;
	}		
	if (preg_match("/Your Apple ID or password was entered incorrectly/i",$result)){
		echo "Authentication failed\n";
		break;
	}		
	if (preg_match("/no report to download/i",$result)){
		echo "No report selected\n";
		break;		
	}	
	if ($i<=1 && !preg_match("/signOutF/i",$result)){
		echo "Not authenticated\n";
		break;		
	}	
			
}
curl_close($ch); 

unlink($cookie);

//make master array with data
if (isset($data)){
	$lines = str_getcsv($data,"\n");
	$headers =  str_getcsv($lines[0],"\t");
	foreach ($lines as $k => $l){
		if ($k == 0) continue;
		$fields = str_getcsv($l,"\t");
		foreach ($fields as $n => $f){
			 $array[$headers[$n]][] = $f;
		}
	}	
}else{
	echo "Did not get data.\n";
	exit;
}

//make array with spot exchange rates for 33 currencies
$currencies = parse_gesmes("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");

foreach ($array['Title / Episode / Season'] as $k => $v){
	if ($array['Product Type Identifier'][$k] == 7){
		$apps[$v]['updates'] += $array['Units'][$k];
	}elseif($array['Product Type Identifier'][$k] == 1){
		$apps[$v]['units'] += $array['Units'][$k];
		$apps[$v]['money'] += extoeur(($array['Units'][$k]*$array['Royalty Price'][$k]),$array['Royalty Currency'][$k],$currencies)*$currencies[USD];		
	}
}

$total = array ('gross'=>0,'paid'=>0,'paid_u'=>0,'free'=>0,'free_u'=>0,'updates'=>0);

foreach ($apps as $n => $a){
	if ($a[money] == 0 ) {
		$total[free] += $a[units];
		$total[free_u] += $a[updates];		
	}	
	if ($a[money] > 0 ){
		 $total[paid] += $a[units];
		 $total[paid_u] += $a[updates];		
	}	
	$total[gross] += $a[money];
}

// Output format: time # total earnings # paid units # free units # paid updates # free updates # monthly prediction
echo @strftime("%d.%m. %H:%M")."#".round($total[gross],2)."#".$total[paid]."#".$total[free]."#".$total[paid_u]."#".$total[free_u]."#".round(($total[gross]/7)*31)."\n";

function extoeur($value,$curr,$currencies){
	$currencies[EUR] = 1;
	if (isset($currencies[$curr])){
		return $value/$currencies[$curr];
	}else{
		echo "Unknown currency $curr";
		return 0;
	}
}

function parse_gesmes ($input){
        $data = xml2php($input);
        foreach ($data as $d){
                 if ($d[tag] == "CUBE"){
                          if ( isset($d[attributes][CURRENCY]) ){
								$return[$d[attributes][CURRENCY]] = $d[attributes][RATE];
                          }
                }
        }
        return $return;
}

function xml2php($file) {
   $xml_parser = xml_parser_create();
   if (!($fp = fopen($file, "r"))) {
       die("Unable to open $file");
   }
   $contents = fread($fp, 4500);
   $contents .= "<tag></tag>";
   fclose($fp);
   xml_parse_into_struct($xml_parser, $contents, $arr_vals);
   xml_parser_free($xml_parser);

   return $arr_vals;
}

?>
